package com.example.demo.service;

import com.example.demo.model.TextDocument;
import com.example.demo.repository.TextDocumentRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class TextDocumentServiceImpl implements TextDocumentService {

    private final TextDocumentRepository textDocumentRepository;

    public TextDocumentServiceImpl(TextDocumentRepository textDocumentRepository) {
        this.textDocumentRepository = textDocumentRepository;
    }

    @Override
    public List<TextDocument> getAllDocuments() {
        return textDocumentRepository.findAll();
    }

    @Override
    public List<TextDocument> getFeaturedDocuments() {
        return textDocumentRepository.findByFeaturedTrue();
    }

    @Override
    public TextDocument getDocumentById(Long id) {
        return textDocumentRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("文档不存在，ID: " + id));
    }

    @Override
    @Transactional
    public TextDocument saveDocument(TextDocument document) {
        return textDocumentRepository.save(document);
    }

    @Override
    @Transactional
    public void deleteDocument(Long id) {
        textDocumentRepository.deleteById(id);
    }

    @Override
    @Transactional
    public void toggleFeatured(Long id) {
        TextDocument document = getDocumentById(id);
        document.setFeatured(!document.isFeatured());
        textDocumentRepository.save(document);
    }
} 